<template>
  <div id="app">
    <router-view />
    <theme-picker />
  </div>
</template>

<script>
import ThemePicker from "@/components/ThemePicker";
import { setToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { getToken, getTokenNew } from "@/api/manage/asset";
export default {
  name: "App",
  components: { ThemePicker },
  data() {
    return {
      pollingTimer: null,
      pollingInterval: 5000, // 轮询间隔，默认5秒
      isInitialized: false, // 初始化状态标记
      initTimeout: null, // 初始化超时定时器
      loadingInstance: null,
    };
  },
  created() {
    // 注释
    this.$store.commit("user/SET_ROLES", ["user"]);

    // 页面初始化时开始轮询
    // this.startPolling();
    console.log(this.$store.state.user, "----");
    const token = this.$store.state.user.token;
    if (token) {
      this.isInitialized = true;
    } else {
      const cookieToken = this.$store.state.user.token;
      if (cookieToken) {
        this.isInitialized = true;
      } else {
        this.showLoading();
        this.initTimeout = setTimeout(() => {
          if (!this.isInitialized) {
            this.hideLoading();
            this.isInitialized = true;
          }
        }, 5000);
      }
    }
  },
  mounted() {
    // 添加iframe消息监听器
    // window.addEventListener("message", this.handleMessage);
    console.log("iframe消息监听器已启动");
    // 开发环境
    // this.init();
  },
  beforeDestroy() {
    // 移除iframe消息监听器
    window.removeEventListener("message", this.handleMessage);
    if (this.initTimeout) {
      clearTimeout(this.initTimeout);
    }
    this.hideLoading();
  },
  methods: {
    showLoading() {
      this.loadingInstance = Loading.service({
        lock: true,
        text: "正在初始化系统，请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0,0,0, 0.7)",
      });
    },
    hideLoading() {
      if (this.loadingInstance) {
        this.loadingInstance.close();
        this.loadingInstance = null;
      }
    },
    init() {
      if (process.env.NODE_ENV === "development") {
        // data=haYSV1vDBR2ABKG5pzDlCSu5OQX1K3daR9UhlcB0wj8MplqSwvkhjTUtI+YE4gcMpj0l/5QB5LSpPOovEeQRwGc65YV0lHaPj+4hk9NqqmD2WHJiyuFId4n6fGI7NBkopgVByBh0z4MA9giM8/+c0jyf5Y0AtFEGoJN9GWva+Ie54k4EciXH3tOt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eXWEXeOaR3661NrFpgTfBiPVE36HoMRrJOMhrKYHEQ==&&systemCode=byznjc
        // data=haYSV1vDBR2ABKG5pzDlCSu5OQX1K3daR9UhlcB0wj8MplqSwvkhjTUtI%20YE4gcMpj0l%2F5QB5LSpPOovEeQRwGc65YV0lHaPj%204hk9NqqmD2WHJiyuFId4n6fGI7NBkopgVByBh0z4MA9giM8%2F%20c0jyf5Y0AtFEGoJN9GWva%20Ie54k4EciXH3tOtvC7vppSga%2FIFHlkcnctUPVjjpQCwCdz0Vla%20KShKfVe4kAT%2FQqzlHV0OBs3PGxGniyv5P4in1l8FpUlqo5vVF02rKoU6yti1nQiEROO%2FWicqaYUd6PNj6dVG31k23%20kD4PpiPx%203%20kNr%2FSQ7Ja%2FDCI%2Fw4D6IUOj07z4Y5gkuJnilt5z%2FI3DyEltWnGPdYQv4NMCwjL3RYjJr4JXQc9SiLRZ7R5%2Fw39tmanedLJ4U0xItMhm0U6EKHdChZ2YOUjPj3nnlbk5jDSbmGYoqixL%20pDleexwob%2FESzjIp2TdqzUMZZQsioXgO%20sjhR1ZpieLK3PByN28kIAszwtaV2OkMKVdr%20ytbh3Mqkv1eXT7Ss4Wxb5V4vfAxDyhYlfP%20I8qSP%20u6JQLpb1jiyVYMklT68aha9OiuTRTi7%20PNu7B45xVTQB9Ax2eQgSfDNYhyWUY1ENJyUp0SRN4dRYLz2wS9anGGoLAwZhznlg4awfNmvsEB09ND7vMutDcw0nJ3NZZz5WW5vdvUfiqCMAcP6wuJFLIk7IeTsnnq%20AJyNIdfkvLG1NY9MVF8gngsAV%2FtGatno9dA3OEWTDqueOhM8uHqc54URwlHqR%20lo%20p1giBEUMdTi5lM0q19W9sO3Vcy9ShWU6TYJdn42oGDq1jdqmK%20CFs%2FFMbQZl2etUmkwE1oWAFT950tPxkp7uqOvDgyECLsTmnggtYNETCJ2keI6KMJIP8JLW4YVMDZL8rwWUczHMAuXfFf5flhhzmn00fkYoNMxAx%20rw1v&encryption=ITJMvRWK4Du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MAcP6wuJFLIk7IeTsnnq+AJyNIdfkvLG1NY9MVF8gngsAV/tGatno9dA3OEWTDqueOhM8uHqc54URwlHqR+lo+p1giBEUMdTi5lM0q19W9sO3Vcy9ShWU6TYJdn42oGDq1jdqmK+CFs/FMbQZl2etUmkwE1oWAFT950tPxkp7uqOvDgyECLsTmnggtYNETCJ2keI6KMJIP8JLW4YVMDZL8rwWUczHMAuXfFf5flhhzmn00fkYoNMxAx+rw1v",
          secret:
            "ITJMvRWK4DuvutuZobFs6CjS4IgMZ4R7/iUV6IvzEkmuvjVvrwf3ZajYGrHyVqG/R8B78PfdeqLT+cTmPA7RSX6ztUMjrlamPvnXNN2cB+R8CTQjwWba90s7+Wy1RMqC1DDyz+FjrTEgleIDLLPx0IYLvrFgyJ41TCtrbL/M1nLLHTNlg43vP4ZAoBacmEJuCRmuwSIoiexcgpuud4zefmav5qM2BRnzK0xVY5W6uDxqYza0CcPL5/Uo0unj95ieqCMz5gnwRizlVYdjfj9RS39VkXNTITzpRKSpgaN7G3BCeXWEXeOaR3661NrFpgTfBiPVE36HoMRrJOMhrKYHEQ==",
          sysCode: "byznjc",
        };
        // 新的接口
        getTokenNew(data).then((res) => {
          if (res.errorCode === "000000") {
            this.$store.commit("user/SET_PARENT_MSG", res.data);
            // 系统中用的token
            this.$store.commit("user/SET_TOKEN", res.data.token);
            this.$nextTick(() => {
              setToken(res.data.token);
            });
          }
        });
      }
    },
    handleMessage(event) {
      // const data = JSON.parse(decodeURIComponent(event.data));
      console.log(event, "接收消息event");
      console.log(event.data, "接收消息event.data");
      // 开发环境使用测试数据
      if (!event.data) return;
      // if (process.env.NODE_ENV === "development") {
      if (event.data === "webpackOk") return;
      if (
        event.data &&
        typeof event.data === "object" &&
        (event.data.type === "webpackOk" ||
          event.data.key === "__VUE_DEVTOOLS_VUE_DETECTED_EVENT__")
      )
        return;

      let decodeData = decodeURIComponent(event.data);
      console.log("解析后的数据decodeData:", data);
      const data = JSON.parse(decodeData);
      console.log("解析后的数据data:", data);

      // 处理从父窗口传递的数据
      getTokenNew(data).then((res) => {
        if (res.errorCode === "000000") {
          this.$store.commit("user/SET_PARENT_MSG", res.data);
          // 系统中用的token
          this.$store.commit("user/SET_TOKEN", res.data.token);
          this.$nextTick(() => {
            setToken(res.data.token);
          });
        }
      });
      // 开发环境
      // const testToken =
      //   "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJtc2ciOiJzdWNjZXNzIiwiY29kZSI6IjIwMCIsInVzZXJfbmFtZSI6IjEwMTgwMCMjIyPmtYvor5XluJDlj7ctMTAxODAwIyMjIzEzMzg2MTIyMTg3Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXSwiZXhwIjoxNzU2OTA2NjMyLCJhdXRob3JpdGllcyI6WyJVU0VSX1JPTEUiXSwianRpIjoiODQxMWJjMTUtZGYwNi00NTdmLWI2MzctYjc2NzIwOTIyMjk2IiwiY2xpZW50X2lkIjoiYzEifQ.JXJsLc8fPBRDfO_DVMJ6B9h17IhzBmo7uebGrpTXi6P9K5OR2jzkqHJPQlsH5rOqrLfPBH3qb_dSdNgH3H-Y-gE8skSnOQCxuIJ7TLQxKPcxUKRlf6ost_uAaEbpOTMdzMyuYpuSZlJiaLCE7seoVHH-WdpMvV9mQX19JCvQy7srp5x9d5oERGlzwAj2gg5ZZImY-ZJOxXSKRubizoF924wJi35II6JZHkH-DOv-nnC-k_TJU4E_NBZ93q0qHNspsotLGbAoFWwLOHPvN7vggDMj0Z7Pi5bLnOkuSBAeC6jveu01lzeuX8A--nfcPXeni7RJyXxYiko9Hlm4m3e4XA";
      // // 这里调接口 获取当前项目token 并存储到项目中
      // getToken(testToken).then((res) => {
      //   console.log(res, "resssssssssssssss");
      //   if (res.errorCode === "000000") {
      //     this.$store.commit("user/SET_PARENT_MSG", res.data);
      //     // 系统中用的token
      //     this.$store.commit("user/SET_TOKEN", res.data.token);
      //     this.$nextTick(() => {
      //       setToken(res.data.token);
      //     });
      //   }
      // });
      // } else {

      // 生成路由并完成初始化
      // this.$store
      //   .dispatch("permission/generateRoutes", data.roles || ["user"])
      //   .then((accessRoutes) => {
      //     console.log("菜单数据", this.$store.state.permission.routes);
      //     this.hideLoading();
      //     this.isInitialized = true;

      //     // 如果当前在根路径，跳转到首页
      //     if (this.$route.path === "/") {
      //       this.$router.push("/index");
      //     }
      //   })
      //   .catch((error) => {
      //     console.error("路由生成失败:", error);
      //     this.hideLoading();
      //     this.isInitialized = true;
      //   });
    },
  },
  watch: {
    "$store.state.user.parentMsg": {
      handler(newVal) {
        console.log(
          "parentMsg changed:",
          JSON.stringify(this.$store.state.user.parentMsg),
        );
      },
      immediate: true,
    },
  },
};
</script>
<style scoped>
#app .theme-picker {
  display: none;
}
</style>
